<script lang="ts" setup>
import type { CommodityClassify, SaveCommodityClassifyVo } from '@/openapi-generator';
import { useCommodityClassifyStore } from '@/stores/commodity-classify';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { message, Modal, type FormInstance } from 'ant-design-vue';
import type { ColumnsType, TableRowSelection } from 'ant-design-vue/es/table/interface';
import { createVNode, onMounted, reactive, ref } from 'vue';
// typescript
const state = reactive({
  visible: false,
  loading: false,
  confirmLoading: false
});
const filterValue = reactive({
  status: undefined as undefined | number,
  keyword: ""
});
const page = reactive({
  current: 10,
  total: 120
});
const classifyStore = useCommodityClassifyStore();
const classifyFirst = ref<CommodityClassify[]>(classifyStore.classifyList.filter(x => !x.parentId));
const formRef = ref<FormInstance>();
const form = reactive<SaveCommodityClassifyVo>({
  id: 0,
  name: "",
  parentId: undefined as any,
  sort: 0,
  thumb: "",
  enabled: true
});
const rules = reactive({
  name: [{ required: true, message: '请输入分类名!' }]
});
const rowSelection: TableRowSelection = {
  checkStrictly: true,
  columnWidth: 60,
  preserveSelectedRowKeys: false,
  onChange: () => {
    // TODO 复选框变化
  }
};
const table = reactive({
  rowSelection,
  loading: false,
  columns: [
    { title: "序号", dataIndex: "index", width: 80, align: 'center' },
    { title: "分类名称", dataIndex: "name" },
    { title: "图标", dataIndex: "icon", align: 'center' },
    { title: "分类等级", dataIndex: "level" },
    { title: "排序", dataIndex: "sort" },
    { title: "状态", dataIndex: "status", width: 100 },
    { title: "操作", dataIndex: "operation", width: 140 }
  ] as ColumnsType,
  data: [] as CommodityClassify[]
});

// 设置表单内容
const setForm = (record: CommodityClassify) => {
  form.id = record.id;
  form.enabled = record.enabled;
  form.name = record.name;
  form.parentId = (record.parentId ? record.parentId : undefined) as any;
  form.sort = record.sort;
  form.thumb = record.icon;
}

// 显示表单
const onShowFormDialog = (record?: CommodityClassify) => {
  formRef.value && formRef.value.resetFields();
  record && setForm(record);
  state.visible = true;
}

// 搜索、条件变化
const onSearch = () => {

}

// 确认提交表单
const onConfirmSubmitForm = async () => {
  try {
    formRef.value && await formRef.value.validate();
  } catch (error) {
    return
  }

  try {
    state.confirmLoading = true;
    await $adminApi.commodityClassifyAddCommodityClassify(form);
  } catch (error) {
    return
  } finally {
    state.confirmLoading = false;
  }

  state.visible = false;
  message.success("操作成功");
  // 重新获取分类列表
  loadCommodityClassifyList();
}

// 更新状态
const onSwitchChange = async (record: CommodityClassify) => {
  setForm(record);
  onConfirmSubmitForm();
}

// 移除分类
const onRemoveClassify = (record: CommodityClassify) => {
  Modal.confirm({
    centered: true,
    title: '确认删除该条数据?',
    icon: createVNode(ExclamationCircleOutlined),
    content: '删除后将不可恢复，请确认',
    onOk: async () => {
      try {
        await $adminApi.commodityClassifyRemoveCommodityClassifyById(record.id);
      } catch (error) {
        return Promise.reject("操作失败");
      }
      loadCommodityClassifyList();
      return Promise.resolve();
    }
  });
}

// 加载商品分类
const loadCommodityClassifyList = async () => {
  try {
    state.loading = true;
    await classifyStore.getClassifyList();
  } catch (error) {
    return
  } finally {
    state.loading = false;
  }
  table.data = classifyStore.classifyList;
  classifyFirst.value = classifyStore.classifyList.filter(x => !x.parentId);
}

onMounted(() => {
  loadCommodityClassifyList();
});
</script>
<script lang="ts">
export default { name: "classificationList" }
</script>

<!-- template -->
<template>
  <section class="container">
    <table-layout v-model:current="page.current" @search="onSearch" :show-page="false">
      <!-- 自定义渲染过滤条件表单 -->
      <template #filter-form>
        <a-form-item label="当前状态">
          <a-input v-model:value="filterValue.keyword" placeholder="分类名称" />
        </a-form-item>
        <a-form-item label="分类名称">
          <a-input v-model:value="filterValue.status" placeholder="分类名称" />
        </a-form-item>
      </template>

      <!-- 表格头部按钮部分 -->
      <template #table-header-btn>
        <a-button type="primary" @click="onShowFormDialog()">+ 添加</a-button>
      </template>

      <!-- 自定义渲染表格部分 -->
      <template #table-content>
        <a-table :loading="state.loading" :size="$config.TABLE_SIZE" bordered row-key="id" :pagination="false" :columns="table.columns"
          :data-source="table.data" :row-selection="table.rowSelection">
          <template #bodyCell="{ column, record, index }">

            <template v-if="column.dataIndex == 'index'">
              <span>{{ index + 1 }}</span>
            </template>

            <template v-if="column.dataIndex == 'name'">
              <span>{{ record.parentId ? '-- ' : ''}}{{ record.name }}</span>
            </template>

            <template v-if="column.dataIndex == 'icon'">
              <p class="icon">
                <img v-if="record.icon" :src="record.icon" />
                <span v-else>-</span>
              </p>
            </template>

            <template v-if="column.dataIndex == 'level'">
              <span>{{ record.parentId ? "二级分类" : "一级分类" }}</span>
            </template>

            <template v-if="column.dataIndex == 'status'">
              <a-switch @change="onSwitchChange(record)" v-model:checked="record.enabled" checked-children="启用" un-checked-children="停用" />
            </template>

            <template v-else-if="column.dataIndex == 'operation'">
              <a-button danger type="link" @click="onRemoveClassify(record)">删除</a-button>
              <a-divider type="vertical" />
              <a-button type="link" @click="onShowFormDialog(record)">编辑</a-button>
            </template>
          </template>
        </a-table>
      </template>
    </table-layout>
  </section>

  <a-modal @ok="onConfirmSubmitForm" :confirm-loading="state.confirmLoading" centered v-model:visible="state.visible" title="编辑分类">
    <div class="modal-body">
      <a-form ref="formRef" :rules="rules" :model="form" :label-col="{ span: 5 }">
        <a-form-item label="分类名称" name="name" >
          <a-input v-model:value="form.name" />
        </a-form-item>

        <a-form-item label="上级分类" name="parentId" >
          <a-select placeholder="请选择分类" v-model:value="form.parentId" :options="classifyFirst.map(x => ({ label: x.name, value: x.id }))" />
        </a-form-item>

        <a-form-item label="分类排序" name="sort" >
          <a-input v-model:value="form.sort" />
        </a-form-item>

        <a-form-item label="分类图标" name="icon" >
          <upload-file accept=".jpg,.png,.jpeg" v-model:value="form.thumb" />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<style lang="less" scoped>
// less
.container {
  height: 100%;

  .icon {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 28px;
      height: 28px;
    }
  }
}
</style>